package com.henry.chatkit.messages.holder

import android.util.Log
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.henry.chatkit.R
import com.henry.chatkit.messages.MessageInfo
import java.util.*

class MessageAudioHolder(itemView: View) : MessageContentHolder(itemView) {

    private lateinit var audioTimeText: TextView
    private lateinit var audioPlayImage: ImageView
    private lateinit var audioContentView: LinearLayout

    override fun getVariableLayout(): Int {
        return R.layout.message_content_audio
    }

    override fun initVariableViews() {
        audioTimeText = rootView.findViewById(R.id.audio_time_tv)
        audioPlayImage = rootView.findViewById(R.id.audio_play_iv)
        audioContentView = rootView.findViewById(R.id.audio_content_ll)
    }

    override fun layoutVariableViews(msg: MessageInfo?, position: Int) {
        if (msg == null) {
            return
        }

        val params = RelativeLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        params.addRule(RelativeLayout.CENTER_VERTICAL)
        if (msg.isSelf) {
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
            params.rightMargin = 1
            audioPlayImage.setImageResource(R.drawable.message_voice_sender_normal)
            audioContentView.removeView(audioPlayImage)
            audioContentView.addView(audioPlayImage, 1)
        } else {
            params.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
            params.leftMargin = 1
            audioPlayImage.setImageResource(R.drawable.message_voice_receiver_normal)
            audioContentView.removeView(audioPlayImage)
            audioContentView.addView(audioPlayImage, 0)

            // 语音未读
            if (!msg.read) {
                val unreadParams = LinearLayout.LayoutParams(40, 20)
                unreadParams.gravity = Gravity.CENTER_VERTICAL
                unreadParams.leftMargin = 10
                unreadAudioText.visibility = View.VISIBLE
                unreadAudioText.layoutParams = unreadParams
            } else {
                unreadAudioText.visibility = View.GONE
            }
        }
        audioContentView.layoutParams = params

        var duration = msg.duration
        if (duration == 0) {
            duration = 1
        }

        val audioParams = msgContentFrame.layoutParams
        audioParams.width = properties.audioMinWidth + duration * properties.audioMargin
        if (audioParams.width > properties.audioMaxWidth) {
            audioParams.width = properties.audioMaxWidth
        }
        msgContentFrame.layoutParams = audioParams
        audioTimeText.text = "$duration''"

    }

}